//
//  SRWorkListViewController.m
//  StoryShow
//
//  Created by CyonLeuMBP on 2017/6/7.
//  Copyright © 2017年 qudiandu.cn. All rights reserved.
//

#import "SRWorkListViewController.h"

#import <MJRefresh/MJRefresh.h>

#import "SRWorkListTableViewCell.h"
#import "SRWorkListItemModel.h"
#import "SRWorkListService.h"

#import "SRWorkDetailViewController.h"

@interface SRWorkListViewController ()<UITableViewDataSource,UITableViewDelegate, UIAlertViewDelegate>

@property (strong, nonatomic) UITableView *tableView;

@property (strong, nonatomic) NSMutableArray *items;
@property (assign, nonatomic) NSInteger pageIndex;
@property (assign, nonatomic) BOOL isEditStatus;
@property (strong, nonatomic) UIButton *editButton;
@property (strong, nonatomic) SRWorkListItemModel *selectedModel;

@end

@implementation SRWorkListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
        // Do any additional setup after loading the view.
    
    self.title = @"我的作品";
    [self setupData];
    [self setupView];
    
    [self showLoadingViewWithCompletedBlock:nil];
    [self queryData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
}

#pragma mark - setup

- (void)setupData {
    self.pageIndex = 0;
    self.items = [@[] mutableCopy];
    self.isEditStatus = NO;
}

- (void)setupView {
    
    WEAKSELF
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 135;
//    self.tableView.contentInset = UIEdgeInsetsMake(15, 0, 0, 0);
    
    [self.tableView registerNib:[UINib nibWithNibName:kSRWorkListTableViewCell bundle:nil] forCellReuseIdentifier:kSRWorkListTableViewCell];
    
    [self.view addSubview:self.tableView];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.top.equalTo(self.view);
    }];
    self.view.backgroundColor = self.tableView.backgroundColor = css.color_2;
    
    
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        weakSelf.pageIndex = 0;
        [weakSelf queryData];
    }];
    
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf queryData];
    }];
    
    UIBarButtonItem *itemSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    itemSpacer.width = -10;
    
    self.editButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.editButton setTitle:@"编辑" forState:UIControlStateNormal];
    self.editButton.frame = CGRectMake(0, 0, 100/2., 90/2.);
    [self.editButton setTitleColor:css.color_4 forState:UIControlStateNormal];
    [self.editButton.titleLabel setFont:css.fontOfH5];
    [self.editButton addTarget:self action:@selector(editButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:self.editButton];
    self.navigationItem.rightBarButtonItems = @[itemSpacer, rightItem];
}

#pragma mark - Query Data


- (void)queryData{
    WEAKSELF
    [SRWorkListService queryWorkListPage:self.pageIndex uid:[SRLoginUser userID] successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        [weakSelf hideLoadingView];
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.tableView.footer endRefreshing];

        if (statusCode == kFZRequestStatusCodeSuccess && responseDataObject) {

            NSArray *addItems = @[];
            if ([responseDataObject isKindOfClass:[NSArray class]]) {
                addItems = responseDataObject;
            }

            if (weakSelf.pageIndex == 0) {
                [weakSelf.items removeAllObjects];
            }

            if ([addItems count] <= 0) {
                    //没有更多
                [weakSelf.tableView.footer noticeNoMoreData];
                if (weakSelf.pageIndex == 0) {
                    [weakSelf emptyLoadingViewWithTitle:nil];
                }

            } else {
                weakSelf.pageIndex += [addItems count];
                [weakSelf.items addObjectsFromArray:addItems];
            }

            [weakSelf.tableView reloadData];

        } else {
            if (weakSelf.pageIndex == 0) {
                [weakSelf failedLoadingViewWithTitle:nil];
            }
        }

    } failureBlock:^(id responseObject, NSError *error) {
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.tableView.footer endRefreshing];

        if ([weakSelf.items count] <= 0) {
            [weakSelf failedLoadingViewWithTitle:nil];
        }

    }];
    
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.items count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SRWorkListTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:kSRWorkListTableViewCell forIndexPath:indexPath];
    cell.isEditStatus = self.isEditStatus;
    
    SRWorkListItemModel *item = self.items[indexPath.row];
    [cell updateCellInfo:item];
    WEAKSELF
    cell.touchDeleteButtonBlock = ^(SRWorkListItemModel *item) {
        [weakSelf touchDeleteButtonAction:item];
    };
    
    return cell;
}


#pragma mark - UITableViewDelegate


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SRWorkListItemModel *item = self.items[indexPath.row];
    
    if (self.isEditStatus) {
        [self touchDeleteButtonAction:item];
    } else {
        SRWorkDetailViewController *vc = [[SRWorkDetailViewController alloc] init];
        vc.show_id = item.show_id;
        vc.listItemModel = item;
        
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        [self deleteWorkWithModel:self.selectedModel];
    }
}

#pragma mark - Event

- (void)touchDeleteButtonAction:(SRWorkListItemModel *)item {
    self.selectedModel = item;
    UIAlertView * alterView=[[UIAlertView alloc] initWithTitle:@"删除作品" message:@"是否确定删除你的配音作品，删除后将无法恢复。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alterView.tag = 1000;
    [alterView show];
}

- (void)deleteWorkWithModel:(SRWorkListItemModel *)item {
    WEAKSELF
    [SRWorkListService deleteWorkWithWorkID:item.identifier successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        if (statusCode == kFZRequestStatusCodeSuccess) {
            [weakSelf showHUDErrorMessage:@"删除成功"];
        } else {
            [weakSelf showHUDErrorMessage:message];
        }
    } failureBlock:^(id responseObject, NSError *error) {
        [weakSelf showHUDErrorMessage:@"删除失败"];
    }];
}

- (void)editButtonClickAction:(UIButton *)button {
    self.isEditStatus = !self.isEditStatus;
    [self.tableView reloadData];
}

- (void)setIsEditStatus:(BOOL)isEditStatus{
    _isEditStatus = isEditStatus;
    
    if (isEditStatus) {
        [UIView setAnimationsEnabled:NO];
        [self.editButton setTitle:@"取消" forState:UIControlStateNormal];
        [UIView setAnimationsEnabled:YES];
    } else {
        [UIView setAnimationsEnabled:NO];
        [self.editButton setTitle:@"编辑" forState:UIControlStateNormal];
        [UIView setAnimationsEnabled:YES];
    }
}

@end
